package com.tudouji.project.bill.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.flow.service.process.service.impl.FlowProcessProxy;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.enums.WlinfoPayStatusEnum;
import com.tudouji.common.enums.WlinfoStatusEnum;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.bill.domain.*;
import com.tudouji.project.bill.mapper.TransferapplyMapper;
import com.tudouji.project.bill.mapper.TransferapplyitemMapper;
import com.tudouji.project.bill.service.ITransferapplyService;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Qaform;
import com.tudouji.project.harvest.mapper.QaformMapper;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import com.tudouji.project.wlinfo.domain.Wlinfo;
import com.tudouji.project.wlinfo.domain.Wlinfoitem;
import com.tudouji.project.wlinfo.mapper.WlinfoMapper;
import com.tudouji.project.wlinfo.mapper.WlinfoitemMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 库房调拨Service业务层处理
 *
 * @author tudouji
 * @date 2021-03-22
 */
@Slf4j
@Service
public class TransferapplyServiceImpl implements ITransferapplyService, IFlowBaseService {
    @Autowired
    private TransferapplyMapper transferapplyMapper;
    @Autowired
    private TransferapplyitemMapper itemService;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private WhoutformServiceImpl whoutformService;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private FlowProcessProxy flowProcessProxy;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    @Autowired
    private WhinformServiceImpl whinformService;
    @Autowired
    private WlinfoMapper wlinfoMapper;
    @Autowired
    private WlinfoitemMapper wlinfoitemMapper;
    @Autowired
    private QaformMapper qaformMapper;
    @Autowired
    private StorehouseroomMapper storehouseroomMapper;


    /**
     * 查询库房调拨
     *
     * @param guid 库房调拨ID
     * @return 库房调拨
     */
    @Override
    public Transferapply selectTransferapplyById(String guid) {
        return transferapplyMapper.selectTransferapplyById(guid);
    }

    @Override
    public Transferapply selectTransferapplyByNewId(Long id) {
        return transferapplyMapper.selectTransferapplyByNewId(id);
    }

    @Override
    public AjaxResult findDetail(Long id) {
        AjaxResult ajaxResult = AjaxResult.success();

        Transferapply apply = transferapplyMapper.selectTransferapplyByNewId(id);
        Qaform qaform = qaformMapper.selectQaformByFoguid(apply.getGuid());

        if (qaform != null) {
            ajaxResult.put("qaforms", qaform);
//            Upimage upimage = new Upimage();
//            upimage.setEvidenceguid(apply.getGuid());
//            upimage.setImagetype("QA");
//            json.put("qaFormImg", JSONArray.fromObject(upimageService.find(upimage), config));
        }

        Whinform whinform = new Whinform();
        whinform.setBusinesscode(apply.getCode());
        List<Whinform> whinforms = whinformService.findDetail(whinform);
        ajaxResult.put("whinform", whinforms);

        Whoutform whoutform = new Whoutform();
        whoutform.setBusinesscode(apply.getCode());
        List<Whoutform> whoutforms = whoutformService.findDetail(whoutform);
        ajaxResult.put("whoutform", whoutforms);
        ajaxResult.put("apply", apply);

        return ajaxResult;
    }

    /**
     * 其他出入库，出入库及之前可以删除；
     * 调拨派车及之前可以删除，
     */
    @Override
    public AjaxResult del(Long id) {
        Transferapply apply = transferapplyMapper.selectTransferapplyByNewId(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        if ((1 == apply.getType() && 40 >= apply.getStatus())
                || (2 == apply.getType() && 59 >= apply.getStatus())
                || (3 == apply.getType() && 49 >= apply.getStatus())) {
            Transferapply transferapply = new Transferapply();
            transferapply.setId(id);
            transferapply.setStatus(0);
            transferapplyMapper.updateTransferapplyById(transferapply);
            //更新待处理任务
            processUtils.updateTaskByOrderId(id, sysUser, Long.valueOf(apply.getFlowid()));
            return AjaxResult.success();
        } else {
            if (1 == apply.getType()) {
                return AjaxResult.error("已派车！");
            }
            if (2 == apply.getType()) {
                return AjaxResult.error("已出库！");
            }
            if (3 == apply.getType()) {
                return AjaxResult.error("已入库！");
            }
        }
        return AjaxResult.error();
    }

    @Override
    public Transferapply selectTransferapplyByCode(String code) {
        return transferapplyMapper.selectTransferapplyByCode(code);
    }

    /**
     * 查询库房调拨列表
     *
     * @param transferapply 库房调拨
     * @return 库房调拨
     */
    @Override
    public List<Transferapply> selectTransferapplyList(Transferapply transferapply) {
        return transferapplyMapper.selectTransferapplyList(transferapply);
    }

    /**
     * 查询库房调拨列表
     *
     * @param transferapply 库房调拨
     * @return 库房调拨
     */
    @Override
    public List<Transferapply> findPagePC(Transferapply transferapply, String functiontype) {
//        int flag = 0;
//        List<Salespermission> permissions = salespermissionService.getPermByScAndFunc(
//                SecurityUtils.getLoginUser().getUser().getTuserId(), functiontype, "4");
//        if (permissions.size() < 1) {
//            permissions = salespermissionService.getPermByScAndFunc(
//                    SecurityUtils.getLoginUser().getUser().getTuserId(), functiontype, "1");
//            if (permissions.size() > 0) {
//                String[] roomids = new String[permissions.size()];
//                for (int i = 0; i < permissions.size(); i++) {
//                    roomids[i] = permissions.get(i).getSrguid();
//                }
//                transferapply.setRoomids(roomids);
//                flag = 1;
//            }
//
//            permissions = salespermissionService.getPermByScAndFunc(
//                    SecurityUtils.getLoginUser().getUser().getTuserId(), functiontype, "2");
//            if (permissions.size() > 0) {
//                String[] departids = new String[permissions.size()];
//                for (int i = 0; i < permissions.size(); i++) {
//                    departids[i] = permissions.get(i).getDepartid();
//                }
//                transferapply.setDepartids(departids);
//                flag = 1;
//            }
//        } else {
//            flag = 1;
//        }
//        if (flag == 1) {
        return transferapplyMapper.findPagePC(transferapply);
//        } else {
//            return new ArrayList<>();
//        }
    }

    /**
     * 新增库房调拨
     *
     * @param transferapply 库房调拨
     * @return 结果
     */
    @Override
    public int insertTransferapply(Transferapply transferapply) {
        return transferapplyMapper.insertTransferapply(transferapply);
    }

    /**
     * 修改库房调拨
     *
     * @param transferapply 库房调拨
     * @return 结果
     */
    @Override
    public int updateTransferapply(Transferapply transferapply) {
        return transferapplyMapper.updateTransferapply(transferapply);
    }

    /**
     * 批量删除库房调拨
     *
     * @param guids 需要删除的库房调拨ID
     * @return 结果
     */
    @Override
    public int deleteTransferapplyByIds(String[] guids) {
        return transferapplyMapper.deleteTransferapplyByIds(guids);
    }

    /**
     * 删除库房调拨信息
     *
     * @param guid 库房调拨ID
     * @return 结果
     */
    @Override
    public int deleteTransferapplyById(String guid) {
        return transferapplyMapper.deleteTransferapplyById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Transferapply apply, String fileIds) throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        if (StringUtils.isNotBlank(apply.getFromsrguid())) {
            Storeroom room = storeroomMapper.selectStoreroomDetailByGuid(apply.getFromsrguid());
            Organization organization = organizationMapper.selectOrganizationById(room.getOrgguid());
            apply.setFromsrId(room.getId());
            apply.setOrgid(room.getOrgguid());
            apply.setOrgId(organization.getId());
            apply.setOrgname(room.getOrgname());
        }
        if (StringUtils.isNotBlank(apply.getTosrguid())) {
            Storeroom room = storeroomMapper.selectStoreroomDetailByGuid(apply.getTosrguid());
            Organization organization = organizationMapper.selectOrganizationById(room.getOrgguid());
            apply.setTosrId(room.getId());
            apply.setToorgid(room.getOrgguid());
            apply.setToOrgId(organization.getId());
            apply.setToorgname(room.getOrgname());
        }
        switch (apply.getType()) {
            case 1:
                apply.setFlowid("28");
                apply.setCode(codeService.getCode("15"));
                break;
            case 2:
                apply.setFlowid("27");
                apply.setCode(codeService.getCode("29"));
                break;
            case 3:
                apply.setFlowid("27");
                apply.setCode(codeService.getCode("29"));
                break;
        }
        String guid = IdUtils.fastSimpleUUID();
        List<Transferapplyitem> items = apply.getItems();
        apply.setGuid(guid);
        apply.setCreateBy(sysUser.getUserId());
        apply.setStatus(9999);
        apply.setOperatorid(sysUser.getTuserId());
        log.info("tuserId: " + sysUser.getTuserId());
        apply.setCreatetime(DateUtils.getNowDate());
        apply.setApplyname(sysUser.getNickName());

        //组织处理


        transferapplyMapper.insertTransferapply(apply);
        BigDecimal shiftweight = new BigDecimal(0);
        for (Transferapplyitem item : items) {
            item.setGuid(IdUtils.fastSimpleUUID());
            item.setTransferguid(guid);
            itemService.insertTransferapplyitem(item);
//			shiftweight = shiftweight.add(item.getShiftweight());
            shiftweight = shiftweight.add(whoutformService.calculateWeight(item.getSpguid(), item.getShiftweight(), null, 3).get("toT"));
        }
        // 更新调拨重量
        Transferapply transfer = new Transferapply();
        transfer.setGuid(guid);
        transfer.setShiftweight(shiftweight);

//        Storeroom storeroomFrom = storeroomMapper.selectStoreroomByGuid(apply.getFromsrguid());
//        apply.setPlatformId(Long.valueOf(storeroomFrom.getId()));
//        if (apply.getTosrguid() != null){
//            Storeroom storeroomTo = storeroomMapper.selectStoreroomByGuid(apply.getTosrguid());
//            apply.setToPlatformId(Long.valueOf(storeroomTo.getId()));
//        }
        apply.setPlatformId(apply.getFromsrId());
        apply.setToPlatformId(apply.getTosrId());
//        transfer.setToOrgId(apply.getToorgId());


        //调拨类型1-库房调拨,2-调整出库 3-调整入库4-产品降级流程(调整出库入库)5-农户库调整入库6-农户库调整出库
        FlowResult result = processUtils.defaultStart(processUtils.getStartNode(Long.parseLong(apply.getFlowid())), apply, fileIds, sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            transfer.setStatus(result.getNextStat());
            transferapplyMapper.updateTransferapply(transfer);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, String imgids, String opinion, Long taskid) {

        Transferapply transferapply = transferapplyMapper.selectTransferapplyByNewId(id);

//        Storeroom storeroomFrom = storeroomMapper.selectStoreroomByGuid(transferapply.getFromsrguid());
//        transferapply.setPlatformId(Long.valueOf(storeroomFrom.getId()));
//        if (transferapply.getTosrguid() != null){
//            Storeroom storeroomTo = storeroomMapper.selectStoreroomByGuid(transferapply.getTosrguid());
//            transferapply.setToPlatformId(Long.valueOf(storeroomTo.getId()));
//        }
        transferapply.setPlatformId(transferapply.getFromsrId());
        transferapply.setToPlatformId(transferapply.getTosrId());
//        transferapply.setToOrgId(transferapply.getToorgId());

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, transferapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(transferapply.getGuid());
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Transferapply transferapply = transferapplyMapper.selectTransferapplyByNewId(id);

//        Storeroom storeroomFrom = storeroomMapper.selectStoreroomByGuid(transferapply.getFromsrguid());
//        transferapply.setPlatformId(Long.valueOf(storeroomFrom.getId()));
//        if (transferapply.getTosrguid() != null){
//            Storeroom storeroomTo = storeroomMapper.selectStoreroomByGuid(transferapply.getTosrguid());
//            transferapply.setToPlatformId(Long.valueOf(storeroomTo.getId()));
//        }
        transferapply.setPlatformId(transferapply.getFromsrId());
        transferapply.setToPlatformId(transferapply.getTosrId());
//        transferapply.setToOrgId(transferapply.getToorgId());


        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, transferapply
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(transferapply.getGuid());
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult financial(Long id, String imgids, String opinion, Long taskid, Integer quality) {

        Transferapply transferapply = transferapplyMapper.selectTransferapplyByNewId(id);
        String srguid = "";
        if (transferapply.getType() == 1 && transferapply.getStatus() > 39) {
//            srguid = transferapply.getTosrguid();
            transferapply.setToPlatformId(transferapply.getTosrId());
        } else {
//            srguid = transferapply.getFromsrguid();
            transferapply.setPlatformId(transferapply.getFromsrId());
        }
//        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(srguid);
//        transferapply.setPlatformId(Long.valueOf(storeroom.getId()));

//        transferapply.setToOrgId(transferapply.getToorgId());


        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, transferapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setGuid(transferapply.getGuid());
            pb.setStatus(result.getNextStat());
            pb.setQuality(quality);
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    @Override
    public List<Transferapply> selectTransferapplyList(Transferapply transferapply, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (transferapply == null) {
            transferapply = new Transferapply();
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(status)) {
            // 待处理
            if (status.equals("00")) {
                startPage();
                transferapply.setCreateBy(sysUser.getUserId());
                return transferapplyMapper.selectApplyPendingList(transferapply);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                transferapply.setStats(stss);
            }
        }
        //查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return transferapplyMapper.selectTransferapplyList(transferapply);
        } else {
            transferapply.setCreateBy(sysUser.getUserId());
            // 是否有组织权限
            List<Salespermission> permissionsOrg = permissionService
                    .getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "7");
            //是否有部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "2");

            startPage();
            if (permissions.size() > 0 || permissionsOrg.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                String[] roomids = new String[permissionsOrg.size()];
                for (int i = 0; i < permissionsOrg.size(); i++) {
                    roomids[i] = permissionsOrg.get(i).getSrguid();
                }
//                transferapply.setRoomids(roomids);
//                transferapply.setDepartids(deptids);
                transferapply.setOrgIds(roomids);
                transferapply.setDeptIds(deptids);
                return transferapplyMapper.selectApplyListByPerm(transferapply);
            } else {
                //查询个人的
                return transferapplyMapper.selectApplyListByUser(transferapply);
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult transferWhin(Long id, List<Whinformitem> items, String imgids, String opinion, Long taskid, SysUser sysUser) {
        log.debug("*****************TransferTask--transferWhin");
        Transferapply transfer = transferapplyMapper.selectTransferapplyByNewId(id);
        boolean fromAuto = (transfer.getAutoType() == 0);//是否自动生成：1是
        if (fromAuto) {
            sysUser = SecurityUtils.getLoginUser().getUser();
        }
        //组装入库单
        Whinform form = new Whinform();

        Storeroom room;
        switch (transfer.getType()) {
            case 1:///调拨入库
                room = storeroomMapper.selectStoreroomByGuid(transfer.getTosrguid());
                form.setStorermguid(transfer.getTosrguid());
                form.setWhintype(2);
                form.setOrgguid(room.getOrgguid());
                form.setOrgname(room.getOrgname());

                /**
                 * 20201228新增  结算组织为 调出库房组织
                 */
                form.setSettlOrgId(transfer.getOrgid());
                form.setSettlOrgName(transfer.getOrgname());
                form.setCurrency(1);
                form.setStorermguid(transfer.getTosrguid());
                break;
            case 3://调整入库
                room = storeroomMapper.selectStoreroomByGuid(transfer.getFromsrguid());
                form.setStorermguid(transfer.getFromsrguid());
                form.setWhintype(7);
                form.setOrgguid(room.getOrgguid());
                form.setOrgname(room.getOrgname());
                if (transfer.getQuality() == 2) {
                    form.setIsCopytoKD(2);
                } else {
                    form.setIsCopytoKD(1);
                }
                break;
            default:
                break;
        }
        form.setDepartmentid(transfer.getDepartid());
        form.setBusinesscode(transfer.getCode());
        form.setFoguid(transfer.getGuid());
        form.setCreatedate(new Date());
        form.setOperatorid(sysUser.getGuid());
//        try {
        return whinformService.saveTransferApplyWhin(imgids, sysUser, form, items, transfer, taskid, opinion, fromAuto);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error();
//        }
    }

    @Override
    @Transactional
    public AjaxResult tranferWhout(Long id, List<Whoutformitem> items, String imgids, String opinion, Long taskid, SysUser sysUser) {
        Transferapply apply = transferapplyMapper.selectTransferapplyByNewId(id);
        boolean fromAuto = (apply.getAutoType() == 0);//是否自动生成：1是
        if (fromAuto) {
            sysUser = SecurityUtils.getLoginUser().getUser();
        }

        //组装入库单
        Whoutform entity = new Whoutform();
        switch (apply.getType()) {
            case 1://调拨出库
                entity.setOuttype(3);
                entity.setSettlOrgId(apply.getToorgid());
                entity.setSettlOrgName(apply.getToorgname());
                entity.setCurrency(1);
                break;
            case 2://其他出库
                entity.setOuttype(6);
                if (apply.getQuality() == 2) {
                    entity.setIsCopytoKD(2);
                } else {
                    entity.setIsCopytoKD(1);
                }
                break;
            default:
                break;
        }
        entity.setSrguid(apply.getFromsrguid());
        entity.setDepartmentid(apply.getDepartid());
        entity.setOrderguid(apply.getGuid());
        entity.setOperatorid(sysUser.getGuid());
        entity.setBusinesscode(apply.getCode());
        for (Whoutformitem item : items) {
            item.setItemguid(item.getScrapitemid());
            item.setCreateBy(sysUser.getUserId());
        }
        if (entity.getOuttype() == 7) {
            entity.setOuttype(6);
        }
        whoutformService.whout(entity, items, false, null);
//        whoutformService.saveTransferWhout(items, entity);
//        BigDecimal loadweight = new BigDecimal(0);
        for (Whoutformitem item : items) {
            Transferapplyitem transferitem = new Transferapplyitem();
            transferitem.setGuid(item.getScrapitemid());
            transferitem.setLoadweight(item.getWeight());
            transferitem.setFromshguid(item.getShrguid());
            // 获取库间名字
            Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(item.getShrguid());
            transferitem.setFromshname(house.getName());

//            loadweight = whoutformService.calculateWeight(item.getSpguid(), item.getWeight(), null, 3).get("toT");
            itemService.updateTransferapplyitem(transferitem);
        }

        apply.setLoadweight(entity.getWeight());
        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(entity.getSrguid());
        apply.setPlatformId(Long.valueOf(storeroom.getId()));
        if (apply.getTosrguid() != null) {
            Storeroom storeroomTo = storeroomMapper.selectStoreroomByGuid(apply.getTosrguid());
            apply.setToPlatformId(storeroomTo.getId());
        }
        if (fromAuto) {
            FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, apply
                    , sysUser);
            if (result.getMsg().equals(ResultParam.SUCCESS)) {
                Transferapply pb = new Transferapply();
                pb.setLoadweight(entity.getWeight());
                pb.setStatus(result.getNextStat());
                pb.setGuid(apply.getGuid());
                transferapplyMapper.updateTransferapply(pb);
                return AjaxResult.success();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(result.getMsg());
            }
        } else {
            return AjaxResult.success();
        }

    }

    /**
     * @Description: 反入库
     * @Author: xiaxl
     * @Date:
     * @Param:
     * @return:
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult whinBack(Long id, String fileIds, String opinion, Long taskid) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Transferapply apply = transferapplyMapper.selectTransferapplyByNewId(id);
        //反入库
        whinformService.newWhinBack(user, apply.getGuid());

//        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(apply.getFromsrguid());
//        apply.setPlatformId(Long.valueOf(storeroom.getId()));
//        if (apply.getTosrguid() != null){
//            Storeroom storeroomTo = storeroomMapper.selectStoreroomByGuid(apply.getTosrguid());
//            apply.setToPlatformId(Long.valueOf(storeroomTo.getId()));
//        }
        apply.setPlatformId(apply.getFromsrId());
        apply.setToPlatformId(apply.getTosrId());
//        apply.setToOrgId(apply.getToorgId());

        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, apply
                , user);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(apply.getGuid());
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult finance(Long id, String fileIds, String opinion, List<Transferapplyitem> items, Long taskid) {
        items.forEach(item -> {
            itemService.updateTransferapplyitem(item);
        });
        return approval(id, fileIds, opinion, taskid);
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult reSendCar(Wlinfo wlinfo, Long id, String imgids, String opinion, Long taskid) {

        log.info("wlinfoId: " + wlinfo.getWlinfoId());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Transferapply transferapply = transferapplyMapper.selectTransferapplyByNewId(id);

        wlinfo.setTranstype(1);
        wlinfo.setDelifactory(transferapply.getFromsrname());
        Date now = DateUtils.getNowDate();
        wlinfo.setCreatetime(now);
        wlinfo.setCargodate(now);

        this.createWlGather(wlinfo, transferapply.getGuid(), transferapply.getCode(), transferapply.getDepartid()
                , transferapply.getToorgid(), transferapply.getToorgname(), transferapply.getDepartname(), sysUser);

//        String srguid  = transferapply.getFromsrguid();
//        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(srguid);
//        transferapply.setPlatformId(Long.valueOf(storeroom.getId()));

        transferapply.setPlatformId(transferapply.getFromsrId());
        transferapply.setToPlatformId(transferapply.getTosrId());
//        transferapply.setToOrgId(transferapply.getToorgId());

        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, transferapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(transferapply.getGuid());
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    public AjaxResult reToSendCar(Long id) {

        Wlinfo wlinfo = new Wlinfo();
        Transferapply transferapply = this.transferapplyMapper.selectTransferapplyByNewId(id);

        Wlinfoitem wlinfoitem = new Wlinfoitem();
        wlinfoitem.setOrderid(transferapply.getGuid());
        wlinfoitem = this.wlinfoitemMapper.selectWlinfoitemByOrderId(transferapply.getGuid());
        if (wlinfoitem == null) {
            Storeroom fromhouse = this.storeroomMapper.selectStoreroomByGuid(transferapply.getFromsrguid());

            Storeroom tohouse = this.storeroomMapper.selectStoreroomByGuid(transferapply.getTosrguid());
            String codeStr = this.codeService.getCode("2");

            wlinfo.setCode(codeStr);
            wlinfo.setDeliprovince(fromhouse.getProvince());
            wlinfo.setDelicity(fromhouse.getCity());
            wlinfo.setDelidistrict(fromhouse.getArea());
            wlinfo.setDeliaddress(fromhouse.getAddress());
            wlinfo.setDelicontact(fromhouse.getContact());
            wlinfo.setDelicontacttel(fromhouse.getContacttel());
            wlinfo.setArriprovince(tohouse.getProvince());
            wlinfo.setArricity(tohouse.getCity());
            wlinfo.setArridistrict(tohouse.getArea());
            wlinfo.setArriaddres(tohouse.getAddress());
            wlinfo.setArricontact(tohouse.getContact());
            wlinfo.setArricontactno(tohouse.getContacttel());
        } else {
            wlinfo = wlinfoMapper.selectWlinfoById(wlinfoitem.getWlinfoid());
        }
        AjaxResult result = AjaxResult.success();
        result.put("transferapply", transferapply);
        result.put("wlinfo", wlinfo);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult whoutBack(Long id, String fileIds, String opinion, Long taskid) {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Transferapply transferapply = transferapplyMapper.selectTransferapplyByNewId(id);

        //反向出库
        //20230918 新增Whoutform参数 zhangfu
        ArrayList<Whoutform> wof = new ArrayList<Whoutform>();
        whoutformService.whoutBack(transferapply.getGuid(), null, wof);
//        whoutformService.whinoutBack(sysUser, transferapply.getGuid(), 1, wof);

        transferapply.setPlatformId(transferapply.getFromsrId());
        transferapply.setToPlatformId(transferapply.getTosrId());
//        transferapply.setToOrgId(transferapply.getToorgId());

        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, transferapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Transferapply pb = new Transferapply();
            pb.setStatus(result.getNextStat());
            pb.setGuid(transferapply.getGuid());
            this.updateTransferapply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }


    /**
     * @return
     * @Author shaodong
     * @Date 14:03 2021/9/26
     * @Param pinghce 1-否 2-是
     * @Param wlinfo 物流信息
     * @Param entity 业务信息
     * @Param user 当前用户
     * @Paramprivate String depguid;
     * private String orgid;
     * private String orgname;
     * private String depname;
     **/
    public void createWlGather(Wlinfo wlinfo, String guid, String code, String depguid, String orgid, String orgname
            , String depname, SysUser user) {
        String wlinfoguid = wlinfo.getWlinfoId();
        delWlInfo(guid);
        if (StringUtils.isEmpty(wlinfoguid)) {
            String mainGuid = createWl(wlinfo, guid, code, depguid, orgid, orgname, depname, user);
            createWlitem(mainGuid, guid, code);
        } else {
            //如果是拼车--生成对应item
            createWlitem(wlinfoguid, guid, code);
        }
    }

    public void delWlInfo(String orderId) {
        //校验是否有拼车订单
        Integer count = wlinfoitemMapper.findPinCount(orderId);
        Wlinfoitem item = wlinfoitemMapper.selectWlinfoitemByOrderId(orderId);
        if (count == 1) {//没有拼车信息，需要删除wlinfo

            Wlinfo info = new Wlinfo();
            info.setGuid(item.getWlinfoid());
            info = wlinfoMapper.selectWlinfoById(item.getWlinfoid());
            if (!info.getPaystatus().equals(WlinfoPayStatusEnum.START.getCode())) {
                throw new RuntimeException("物流支付状态：非初始");
            }
            wlinfoMapper.deleteWlinfoById(item.getWlinfoid());
        }
        if (item != null) {
            //删除item
            wlinfoitemMapper.deleteWlinfoitemById(item.getGuid());
        }
    }

    public String createWl(Wlinfo wlinfo, String guid, String code, String depguid, String orgid, String orgname
            , String depname, SysUser user) {
//        settingDeliProv(wlinfo); // 发货地址
//        settingArriProv(wlinfo); // 收货地址
        wlinfo.setOperatorid(user.getGuid());
        wlinfo.setOperator(user.getNickName());
        wlinfo.setCode(codeService.getCode("2"));
        wlinfo.setStatus(WlinfoStatusEnum.UNDELIVER.getCode());
        wlinfo.setFlowid("16");
        wlinfo.setRelatedid(guid);
        wlinfo.setDepartid(depguid);
        wlinfo.setDepartname(depname);
        wlinfo = setWlSort(wlinfo, code);
        //销售订单下单组织写入物流单的结算组织 ,销售sorgguid 调拨的toorgid
        wlinfo.setPaystatus(WlinfoPayStatusEnum.START.getCode());

        System.out.println("-------whlinfo org --------" + wlinfo.getOrgid());
        System.out.println("-------whlinfo org --------" + wlinfo.getOrgname());

        if (StringUtils.isBlank(wlinfo.getOrgid())) {
            wlinfo.setOrgid(orgid);
        }
        if (StringUtils.isBlank(wlinfo.getOrgname())) {
            wlinfo.setOrgname(orgname);
        }
        String wlGuid = IdUtils.fastSimpleUUID();
        wlinfo.setGuid(wlGuid);
        wlinfoMapper.insertWlinfo(wlinfo);
        return wlGuid;
    }

    public Wlinfo setWlSort(Wlinfo wlinfo, String sellcode) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        Date now = DateUtils.getNowDate();
        wlinfo.setCreatetime(now);
        wlinfo.setSort(simpleDateFormat.format(now) + sellcode + "99");
        return wlinfo;
    }

    private void createWlitem(String mainGuid, String orderid, String code) {
        Wlinfoitem item = new Wlinfoitem();
        item.setWlinfoid(mainGuid);
        item.setLinkcode(code);
        item.setOrderid(orderid);
        item.setWlstatus("0");
        item.setGuid(IdUtils.fastSimpleUUID());
        wlinfoitemMapper.insertWlinfoitem(item);
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return selectTransferapplyByNewId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return selectTransferapplyByCode(code);
    }
}
